package com.zhipu.balance.ui.vm.home.calculate.dami

import android.annotation.SuppressLint
import android.text.TextUtils
import androidx.databinding.ObservableField
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.constant.TimeConstants
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.TimeUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.zhipu.balance.common.Constants
import com.zhipu.balance.listener.ChooseClickCallback
import com.zhipu.balance.listener.SerialPortListener
import com.zhipu.balance.mobile.dao.NumberDao
import com.zhipu.balance.mobile.dao.RecordDaMiDao
import com.zhipu.balance.mobile.event.RecordCorn
import com.zhipu.balance.mobile.event.RecordDaMi
import com.zhipu.balance.pop.ConfirmPopup
import com.zhipu.balance.remotedata.systemapi.SystemApiService
import com.zhipu.balance.ui.home.calculate.dami.*
import com.zhipu.balance.ui.home.calculate.dami.adapter.DaMiAdapter
import com.zhipu.balance.ui.vm.BaseViewModel
import com.zhipu.balance.utils.InitializeUtils
import com.zhipu.balance.utils.OpenSerialPort
import com.zhipu.balance.utils.data.DisposeUtils
import com.zhipu.balance.utils.print.dami.DaMiPrintUtils
import com.zhipu.balance.utils.upload.dami.DaMiUploadUtils
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit

/**
 * 功能计算-稻谷
 */
class DaMiViewModel(mSystemApiService : SystemApiService) : BaseViewModel(mSystemApiService), SerialPortListener,ChooseClickCallback {
    /**
     * 称重重量
     */
    var weighing = ObservableField("0.00")

    /**
     * 去皮
     */
    var peel = ObservableField(false)

    /**
     * 位置
     */
    var mPosition = MutableLiveData(0)

    /**
     * 编号
     */
    var mNumber = ObservableField("")

    /**
     * 日期
     */
    var mInspectionDate = ObservableField("")

    /**
     * 记录大米
     */
    var mRecordDaMi = RecordDaMi()



    /**
     * 适配器
     */
    var mDaMiAdapter : DaMiAdapter? = null

    /**
     * 是否显示
     */
    var subdivide = ObservableField(false)

    /**
     *  不完善细分
     */
    var mImperfectSubdivision : MutableLiveData<Boolean> = MutableLiveData(SPUtils.getInstance().getBoolean("ImperfectSubdivision",false))


    /**
     *  Fragment集合
     */
    var mFragments = MutableLiveData<List<Fragment>>()

    /**
     * 大米杂质
     */
    var mDaMiImpurityFragment = DaMiImpurityFragment(mRecordDaMi)

    /**
     * 大米不完善粒
     */
    var mDaMiFaultinessFragment = DaMiFaultinessFragment(mRecordDaMi)


    /**
     * 大米碎米
     */
    var mDaMiBrokenFragment = DaMiBrokenFragment(mRecordDaMi)

    /**
     * 大米黄粒米
     */
    var mDaMiYellowGrainFragment = DaMiYellowGrainFragment(mRecordDaMi)

    /**
     * 大米互混
     */
    var mDaMiIintermixingFragment = DaMiIintermixingFragment(mRecordDaMi)


    init {
        OpenSerialPort.onSerialPortListener(this)
        /**
         * 每隔milliseconds毫秒后执行next操作
         */
        Observable.interval(100, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(object :
            Observer<Long> {

            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: Long) {
                /**
                 * 重量輸出命令
                 */
                OpenSerialPort.output()
            }

            override fun onError(e: Throwable) {
            }

            override fun onComplete() {
            }

        })
        /**
         * Fragment适配器
         */
        var mFragmentList = mutableListOf<Fragment>()

        //大米杂质
        mFragmentList.add(mDaMiImpurityFragment)
        //大米不完善粒
        mFragmentList.add(mDaMiFaultinessFragment)
        //大米碎米
        mFragmentList.add(mDaMiBrokenFragment)
        //大米黄粒米
        mFragmentList.add(mDaMiYellowGrainFragment)
        //大米互混
        mFragmentList.add(mDaMiIintermixingFragment)


        /**
         * Fragment集合
         */
        mFragments.postValue(mFragmentList)
        /**
         * 适配器
         */
        mDaMiAdapter = DaMiAdapter(this);

    }


    /**
     * 切换
     */
    fun switchover(ImperfectSubdivision : Boolean){
        mDaMiFaultinessFragment.switchover(ImperfectSubdivision)
    }





    /**
     * 重量回调
     */
    override fun itemClicked(event: ByteArray?) {
        /**
         * 数值
         */
        val numericalValue = ConvertUtils.bytes2HexString(event)
        if (event!!.size >= 10) {
            if (numericalValue == Constants.FARMAR_500) {
                weighing.set("砝码500")
            } else if (numericalValue == Constants.FARMAR_1000) {
                weighing.set("砝码1000")
            } else if (numericalValue == Constants.FARMAR_2000) {
                weighing.set("砝码2000")
            }else if (numericalValue == Constants.FARMAR_3000) {
                weighing.set("砝码3000")
            } else if (ConvertUtils.bytes2HexString(event) == Constants.CALIBRATION_500) {
                weighing.set("完成定标")
            } else if (ConvertUtils.bytes2HexString(event) == Constants.OVERLOAD) {
                weighing.set("超重")
            } else if (ConvertUtils.bytes2HexString(event) == Constants.SEND_GO_START) {
                InitializeUtils.getDefaultMaker()?.show("去皮成功")
                peel.set(false)
            }  else if (ConvertUtils.bytes2HexString(event) == Constants.SHIELD) {
                weighing.set("校准中")
            } else {
                if(peel.get() == true){
                    /**
                     * 置零命令
                     */
                    OpenSerialPort.ZeroOrder()
                }
                var weight = DisposeUtils.balanceCorrection(event)
                //大米杂质
                mDaMiImpurityFragment.setWeighing(weight)
                //大米不完善粒
                mDaMiFaultinessFragment.setWeighing(weight)
                //大米碎米
                mDaMiBrokenFragment.setWeighing(weight)
                //大米黄粒米
                mDaMiYellowGrainFragment.setWeighing(weight)
                //大米互混
                mDaMiIintermixingFragment.setWeighing(weight)

                weighing.set(weight)
            }
        }
    }


    /**
     * Fragment回调
     */
    @SuppressLint("NotifyDataSetChanged")
    override fun onChooseClickCallback(mInt: Int) {
        mDaMiAdapter?.notifyDataSetChanged()
        mPosition.postValue(mInt)
        when(mInt){
            0 ->{
                subdivide.set(false)
                //大米杂质
                mDaMiImpurityFragment.updateRecordRice(mRecordDaMi)
            }
            1 ->{
                subdivide.set(true)
                //大米不完善粒
                mDaMiFaultinessFragment.updateRecordRice(mRecordDaMi)
            }
            2 ->{
                subdivide.set(false)
                //大米碎米
                mDaMiBrokenFragment.updateRecordRice(mRecordDaMi)
            }
            3 ->{
                subdivide.set(false)
                //大米黄粒米
                mDaMiYellowGrainFragment.updateRecordRice(mRecordDaMi)
            }
            4 ->{
                subdivide.set(false)
                //大米互混
                mDaMiIintermixingFragment.updateRecordRice(mRecordDaMi)
            }
        }
    }



    /**
     * 更新数据
     */
    fun UpdatePage(productCategoryText : String){
        var mRecordDaMi = RecordDaMiDao.getInstance().QueryByNumber(productCategoryText)
        if(mRecordDaMi.recordDaMiId > 0){
            this.mRecordDaMi = mRecordDaMi
            //日期
            mInspectionDate.set(TimeUtils.millis2String(mRecordDaMi.inspectionDate))
            //大米杂质
            mDaMiImpurityFragment.updateRecordRice(mRecordDaMi)
            //大米不完善粒
            mDaMiFaultinessFragment.updateRecordRice(mRecordDaMi)
            //大米碎米
            mDaMiBrokenFragment.updateRecordRice(mRecordDaMi)
            //大米黄粒米
            mDaMiYellowGrainFragment.updateRecordRice(mRecordDaMi)
            //大米互混
            mDaMiIintermixingFragment.updateRecordRice(mRecordDaMi)
        }else{
            //唯一识别码
            mRecordDaMi.uniqueId = productCategoryText
            //日期
            mInspectionDate.set(TimeUtils.millis2String(TimeUtils.getNowMills()))
        }
        //编号
        mNumber.set(productCategoryText)

    }

    /**
     * 释放更新页面
     */
    fun releaseRecordRice(){
        mRecordDaMi = RecordDaMi()
        //大米杂质
        mDaMiImpurityFragment.updateRecordDaMi(mRecordDaMi)
        mDaMiImpurityFragment.releaseRecordRice()
        //大米不完善粒
        mDaMiFaultinessFragment.updateRecordDaMi(mRecordDaMi)
        mDaMiFaultinessFragment.releaseRecordRice()
        //大米碎米
        mDaMiBrokenFragment.updateRecordDaMi(mRecordDaMi)
        mDaMiBrokenFragment.releaseRecordRice()
        //大米黄粒米
        mDaMiYellowGrainFragment.updateRecordDaMi(mRecordDaMi)
        mDaMiYellowGrainFragment.releaseRecordRice()
        //大米互混
        mDaMiIintermixingFragment.updateRecordDaMi(mRecordDaMi)
        mDaMiIintermixingFragment.releaseRecordRice()
        //编号
        mNumber.set("")
        //日期
        mInspectionDate.set("")
    }



    /**
     * 更新页面
     */
    fun updatePage(mRecordDaMi : RecordDaMi){
        this.mRecordDaMi = mRecordDaMi
        //编号
        mNumber.set(mRecordDaMi.uniqueId)
        //日期
        mInspectionDate.set(TimeUtils.millis2String(mRecordDaMi.inspectionDate))
        //大米杂质
        mDaMiImpurityFragment.updateRecordRice(mRecordDaMi)
        //大米不完善粒
        mDaMiFaultinessFragment.updateRecordRice(mRecordDaMi)
        //大米碎米
        mDaMiBrokenFragment.updateRecordRice(mRecordDaMi)
        //大米黄粒米
        mDaMiYellowGrainFragment.updateRecordRice(mRecordDaMi)
        //大米互混
        mDaMiIintermixingFragment.updateRecordRice(mRecordDaMi)
    }



    /**
     * 保存
     */
    fun save(){
        var mConfirmPopup = ConfirmPopup(object : ChooseClickCallback{
            override fun onChooseClickCallback(mInt: Int) {
                if(mInt == 0){
                    //唯一识别码
                    mRecordDaMi.uniqueId = mNumber.get()
                    //判断
                    if(mRecordDaMi.recordDaMiId > 0){
                        //设备码
                        mRecordDaMi.deviceId = SPUtils.getInstance().getString("DeviceCode")
                        mRecordDaMi.update()
                    }else{
                        //设备码
                        mRecordDaMi.deviceId = SPUtils.getInstance().getString("DeviceCode")
                        if(mRecordDaMi.save()){
                            /**
                             * 上传
                             */
                            val NetworkSettings = SPUtils.getInstance().getString("NetworkSettings")
                            if(TextUtils.isEmpty(NetworkSettings)){
                                //外网上传大米天平数据
                                DaMiUploadUtils.uploadTrueRiceBalanceInfo(mRecordDaMi,null)
                            }else{
                                //内网上传大米天平数据
                                DaMiUploadUtils.IntranetUploadTrueRiceBalanceInfo(mRecordDaMi,null)
                            }
                        }
                    }
                    /**
                     * 释放更新页面
                     */
                    releaseRecordRice()
                    /**
                     * 数量加一
                     */
                    SPUtils.getInstance().put("number", SPUtils.getInstance().getInt("number") + 1)
                }
            }
        },"确认要进行上传并保存吗\n确认之后会进行新一轮的计算")
        XPopup.Builder(ActivityUtils.getTopActivity())
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .autoOpenSoftInput(false)
            .asCustom(mConfirmPopup)
            .show()
    }


    /**
     * 打印
     */
    fun print(){
        if(InitializeUtils.isLinkPrinter()){
            var mConfirmPopup = ConfirmPopup(object : ChooseClickCallback{
                override fun onChooseClickCallback(mInt: Int) {
                    if(mInt == 0){
                        DaMiPrintUtils.DaMiPrinting(mRecordDaMi)
                    }
                }
            },"确认需要打印吗?")
            XPopup.Builder(ActivityUtils.getTopActivity())
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                .autoOpenSoftInput(false)
                .asCustom(mConfirmPopup)
                .show()
        }else{
            InitializeUtils.getDefaultMaker()?.show("正在链接打印机")
            InitializeUtils.LinkPrinterModel(ActivityUtils.getTopActivity())
        }
    }

    /**
     * 去皮
     */
    fun peel(){
        InitializeUtils.getDefaultMaker()?.show("正在去皮请稍后")
        /**
         * 去皮
         */
        peel.set(true)
        /**
         * 置零命令
         */
        OpenSerialPort.ZeroOrder()
    }

    /**
     * 计算
     */
    fun calculation(){
        when(mPosition.value){
            0->{
                //大米杂质
                mDaMiImpurityFragment.calculation()
            }
            1->{
                //大米不完善粒
                mDaMiFaultinessFragment.calculation()
            }
            2->{
                //大米碎米
                mDaMiBrokenFragment.calculation()
            }
            3->{
                //大米黄粒米
                mDaMiYellowGrainFragment.calculation()
            }
            4->{
                //大米互混
                mDaMiIintermixingFragment.calculation()
            }
        }
        /**
         *  编号
         */
        if(TextUtils.isEmpty(mNumber.get())){
            var number = NumberDao.getInstance().acquireNumber()
            if(null != number){
                if(SPUtils.getInstance().getLong("NumberedDate") > 0){
                    val DAY = TimeUtils.getTimeSpan(
                        SPUtils.getInstance().getLong("NumberedDate"),
                        TimeUtils.getNowMills(),
                        TimeConstants.DAY
                    )
                    if (DAY == 0L) {
                        val numberString: String = number.name + SPUtils.getInstance().getInt("number", 1)
                        mRecordDaMi.uniqueId = numberString
                        mNumber.set(numberString)
                    }else{
                        SPUtils.getInstance().put("number", 1)
                        SPUtils.getInstance().put("NumberedDate", TimeUtils.getNowMills())
                        val numberString: String = number.name + SPUtils.getInstance().getInt("number", 1)
                        mRecordDaMi.uniqueId = numberString
                        mNumber.set(numberString)
                    }
                }
            }
        }
        /**
         * 日期
         */
        var getNowMills = TimeUtils.getNowMills()
        mInspectionDate.set(TimeUtils.millis2String(getNowMills))
        mRecordDaMi.inspectionDate = getNowMills
    }
    /**
     * 主菜单
     */
    fun mainMenu(){
        var mConfirmPopup = ConfirmPopup(object : ChooseClickCallback{
            override fun onChooseClickCallback(mInt: Int) {
                if(mInt == 0){
                    ActivityUtils.finishActivity(DaMiActivity::class.java)
                }
            }
        },"返回主菜单会导致当前数据丢失")
        XPopup.Builder(ActivityUtils.getTopActivity())
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .autoOpenSoftInput(false)
            .asCustom(mConfirmPopup)
            .show()
    }
}